package com.xiaoh.dormitoryrepairreportbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoh.dormitoryrepairreportbackend.constant.UserConstant;
import com.xiaoh.dormitoryrepairreportbackend.mapper.MaintenanceSkillMapper;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.skill.SkillStatsResponse;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.GeneralUser;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.MaintenanceSkill;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.RepairCategory;
import com.xiaoh.dormitoryrepairreportbackend.service.GeneralUserService;
import com.xiaoh.dormitoryrepairreportbackend.service.MaintenanceSkillService;
import com.xiaoh.dormitoryrepairreportbackend.service.RepairCategoryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 维修工技能表 服务实现类
 */
@Service
public class MaintenanceSkillServiceImpl extends ServiceImpl<MaintenanceSkillMapper, MaintenanceSkill>
        implements MaintenanceSkillService {

    @Resource
    private GeneralUserService generalUserService;

    @Resource
    private RepairCategoryService repairCategoryService;

    @Override
    public List<Long> getMaintenanceIdsByCategoryId(Integer categoryId) {
        QueryWrapper<MaintenanceSkill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        
        List<MaintenanceSkill> skills = this.list(queryWrapper);
        return skills.stream()
                .map(MaintenanceSkill::getUserId)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<Integer> getCategoryIdsByUserId(Long userId) {
        QueryWrapper<MaintenanceSkill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        List<MaintenanceSkill> skills = this.list(queryWrapper);
        return skills.stream()
                .map(MaintenanceSkill::getCategoryId)
                .collect(Collectors.toList());
    }

    @Override
    public boolean addMaintenanceSkill(Long userId, Integer categoryId) {
        // 检查是否已存在
        QueryWrapper<MaintenanceSkill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("category_id", categoryId);
        
        if (this.count(queryWrapper) > 0) {
            return true; // 已存在，返回成功
        }
        
        MaintenanceSkill skill = new MaintenanceSkill();
        skill.setUserId(userId);
        skill.setCategoryId(categoryId);
        
        return this.save(skill);
    }

    @Override
    public boolean removeMaintenanceSkill(Long userId, Integer categoryId) {
        QueryWrapper<MaintenanceSkill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("category_id", categoryId);
        
        return this.remove(queryWrapper);
    }

    @Override
    public SkillStatsResponse getSkillStats() {
        SkillStatsResponse stats = new SkillStatsResponse();

        // 1. 查询维修工总数
        QueryWrapper<GeneralUser> maintenanceWrapper = new QueryWrapper<>();
        maintenanceWrapper.eq("user_type", UserConstant.UserType.MAINTENANCE);
        Long totalMaintenanceWorkers = generalUserService.count(maintenanceWrapper);
        stats.setTotalMaintenanceWorkers(totalMaintenanceWorkers);

        // 2. 查询有技能的维修工数量（去重）
        QueryWrapper<MaintenanceSkill> skillWrapper = new QueryWrapper<>();
        skillWrapper.select("DISTINCT user_id");
        List<MaintenanceSkill> distinctSkills = this.list(skillWrapper);
        Long skilledMaintenanceWorkers = (long) distinctSkills.size();
        stats.setSkilledMaintenanceWorkers(skilledMaintenanceWorkers);

        // 3. 查询技能总数（维修类别总数）
        QueryWrapper<RepairCategory> categoryWrapper = new QueryWrapper<>();
        Long totalSkills = repairCategoryService.count(categoryWrapper);
        stats.setTotalSkills(totalSkills);

        // 4. 查询技能分配总数（维修工-技能关联记录总数）
        Long totalSkillAssignments = this.count();
        stats.setTotalSkillAssignments(totalSkillAssignments);

        return stats;
    }
}
